package plugin;

import java.net.URL;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class MyHibernatePlugIn implements PlugIn {

	private Logger logger = Logger.getLogger(MyHibernatePlugIn.class);

	public static final String KEY_NAME = MyHibernatePlugIn.class.getName();
	private String path = null; // "/hibernate.cfg.xml";
	private Configuration config;
	private SessionFactory factory;

	public void setPath(String path) {
		this.path = path;
	}

	@Override
	public void destroy() {
		try {
			factory.close();
		} catch (HibernateException e) {
			logger.error("destroy NO pudo cerrar la Hibernate session factory",
					e);
		}
	}

	@Override
	public void init(ActionServlet actionServlet, ModuleConfig moduleConfig)
			throws ServletException {

		logger.info("Entrando en init");

		try {
			// save the Hibernate session factory into the servlet context
			URL url = MyHibernatePlugIn.class.getResource(path);
			config = new Configuration().configure(url);
			factory = config.buildSessionFactory();
			actionServlet.getServletContext().setAttribute(KEY_NAME, factory);

		} catch (MappingException e) {
			logger.error(
					"ini NO pudo guardar la Hibernate session factory en el contexto del servlet",
					e);
			throw new ServletException("init", e);
		} catch (HibernateException e) {
			logger.error(
					"ini NO pudo guardar la Hibernate session factory en el contexto del servlet",
					e);

			throw new ServletException("init", e);
		}

		logger.info("Saliendo de init factory:" + factory);
	}

}
